var express = require('express');
var router = express.Router();
const { jwt, jwtKey } = require('../server_jwt');
let db = require('../db');

const users = [
    { id: 1, name: 'admin', password: "123456"},
    { id: 2, name: 'user1', password: "123456" },
    { id: 3, name: 'user2', password: "123456" },
    { id: 4, name: 'user3', password: "123456" },
];

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/login', function (req, res, next) {
    if (!req.body.username) {
        res.send({ msg: "用户名为空", login_status: false });
        return;
    } else if (!req.body.password) {
        res.send({ msg: "密码为空", login_status: false });
        return;
    }

    // for (let i = 0; i < users.length; i++) {
    //     if (users[i].name == req.body.username && users[i].password == req.body.password) {
    //         // 登录成功生成jwt
    //         let token = jwt.sign({ name: users[i].name, uid: users[i].id }, jwtKey, { expiresIn: '168h' });
    //         // console.log(token);
    //         // console.log({ msg: "登录成功", jwt: token, login_status: true, username: users[i].name });
    //         res.send({ msg: "登录成功", jwt: token, login_status: true, username: users[i].name, uid: users[i].id });
    //         return;
    //     }
    // }
    let sql_post = 'select id, name from users where name=? and password=? limit 1';
    let data = [req.body.username, req.body.password];

    db.query(sql_post, data, (err, result) => {
        if (err) {
            console.log(err.message);
        }
        console.log("result", result);
        if (result.length == 1) {
            let token = jwt.sign({ name: result[0].name, uid: result[0].id }, jwtKey, { expiresIn: '168h' });
            res.send({ msg: "登录成功", jwt: token, login_status: true, username: result[0].name, uid: result[0].id });
        } else {
            // 登录失败
            res.send({ msg: "账号或密码错误" });
        }
    });
});

router.post('/checkLogin', function (req, res, next) {
    if (!req.body.jwt) {
        res.send({ msg: "令牌为空", login_status: false });
    } else {
        jwt.verify(req.body.jwt, jwtKey, (err, decoded) => {
            if (err) {
                // 解析 jwt 出现错误
                res.send({msg: "登录验证失败，请重新登录", login_status: false});
            } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
                // jwt 登录超时，需要重新登录
                res.send({msg: "登录超时:", login_status: false});
            } else {
                // jwt 认证成功 (严谨一点需要去数据库里查找这个用户是否存在才行)
                res.send({msg: "认证登录成功:", login_status: true});
            }
        });
    }
});

module.exports = router;
